package com.xcm.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xcm.cache.RedisCacheDao;
import com.xcm.config.CustomProperties;
import com.xcm.exception.ServiceException;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取用户信息工具类
 */
public class GetUserUtils {
	/**
	 * 获取用户信息
	 *
	 * @param request          HttpServletRequest
	 * @param redisCacheDao    RedisCacheDao
	 * @param customProperties CustomProperties
	 * @return JSONObject
	 */
	public static JSONObject getUser(HttpServletRequest request, RedisCacheDao redisCacheDao, CustomProperties customProperties) throws ServiceException {
		if (request == null || redisCacheDao == null || customProperties == null) {
			throw new ServiceException("输入参数不能为空");
		}
		Object cookieNameObj = request.getAttribute(customProperties.getCookieName());
		if (cookieNameObj != null) {
			String key = DESUtils.decrypt(String.valueOf(cookieNameObj), customProperties.getSecretKey());
			Object cache = redisCacheDao.getCache(customProperties.getCookieName(), key);
			if (cache != null) {
				JSONObject jsonObject = JSON.parseObject(String.valueOf(cache));
				if (jsonObject == null) {
					return null;
				}
				JSONObject userJsonObj = jsonObject.getJSONObject("user");
				if (userJsonObj == null) {
					return null;
				}
				return userJsonObj;
			}
		}
		return null;
	}
}
